﻿using Step4.Unit7.Service.utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZhiJiao.Dal;
using ZhiJiao.Models.Entities;
using ZhiJiao.Service.Abstracts;
using ZhiJiao.Service.Dto;

namespace ZhiJiao.Service.Services
{
    public class MemeberService : IMemberServicec
    {
        private readonly ICurrentUser _currentUser;
        private readonly ZJDbContext _db;
        private readonly BackJson _res;

        public MemeberService(ICurrentUser currentUser, ZJDbContext dbContext, BackJson res)
        {
            _currentUser = currentUser;
            _db = dbContext;
            _res = res;
        }

        /// <summary>
        /// 获取会员列表
        /// </summary>
        public async Task<BackJson> GetMemeberList(string? filterName,int page,int pageSize)
        {
            try
            {
                long count = 0;
                var ins = _currentUser.User.Instruction;
                var query = _db.Members.AsQueryable();
                query.Where(m => m.Instruction == ins);
                if (!string.IsNullOrEmpty(filterName))
                {
                    query.Where(m => m.Name.Contains(filterName) || (m.Student != null && m.Student.Name.Contains(filterName)));
                }
                count = query.Count();
                //分页
                query.Skip((page-1)*pageSize).Take(pageSize);
                query.OrderBy(m => m.CreateTime);
                var list = query.ToList().Select(m => new
                {
                    id = m.Id,
                    name = m.Name,
                    memberLevel = m.MemberLevel.ToDescription(),
                    instruction = m.Instruction.Name,
                    student = m.Student != null ? m.Student.Name : null,
                    createTime = m.CreateTime?.ToString("yyyy-MM-dd")
                });
                _res.code = 0;
                _res.data = new { 
                    list =list,
                    totalCount =count
                };
            }
            catch (Exception e)
            {
                _res.code = 1;
                _res.msg = e.Message;
            }
           
            return _res;
        }
    }
}
